/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Tela;

import Conexao.ConectaBD;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;

/**
 *
 * @author Thalyson
 */
public class Tela_CadastrarUsuario extends javax.swing.JFrame {

    Connection conecta;
    PreparedStatement pst;
    ResultSet rs;

    public Tela_CadastrarUsuario() throws ClassNotFoundException {
        initComponents();
        setSize(665, 427);
        conecta = ConectaBD.conectabd();
        listarUsuarios();
        setLocationRelativeTo(null);
    }

    public void cadastrarUsuario() {
        String sql = "Insert into login (USUARIO,SENHA,NIVEL) values(?,?,?)";

        if (tf_usuario.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Campo USUÁRIO é Obrigatório", "Aviso", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (tf_senha.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Campo SENHA é Obrigatório", "Aviso", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (cb_nivel.getSelectedItem().equals("NÍVEL DE ACESSO")) {
            JOptionPane.showMessageDialog(null, "Campo Nível é Obrigatório", "Aviso", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try {
            pst = conecta.prepareStatement(sql);
            pst.setString(1, tf_usuario.getText());
            pst.setString(2, tf_senha.getText());
            pst.setString(3, (String) cb_nivel.getSelectedItem());
            pst.execute();
            JOptionPane.showMessageDialog(null, "Cadastrado com sucesso!", "Cadastrado com sucesso", JOptionPane.INFORMATION_MESSAGE);
            listarUsuarios();
            Limpar();
        } catch (SQLException error) {
            JOptionPane.showMessageDialog(null, error);
            listarUsuarios();
        }
    }

    public void listarUsuarios() {
        String sql = "Select *from login order by id Asc";
        try {
            pst = conecta.prepareStatement(sql);
            rs = pst.executeQuery();
            jt_usuarios.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException error) {
            JOptionPane.showMessageDialog(null, error);
        }
    }

    public void mostraUsuarios() {
        int seleciona = jt_usuarios.getSelectedRow();
        tf_id.setText(jt_usuarios.getModel().getValueAt(seleciona, 0).toString());
        tf_usuario.setText(jt_usuarios.getModel().getValueAt(seleciona, 1).toString());
        tf_senha.setText(jt_usuarios.getModel().getValueAt(seleciona, 2).toString());
        cb_nivel.setSelectedItem(jt_usuarios.getModel().getValueAt(seleciona, 3).toString());
    }

    public void Limpar() {
        tf_usuario.setText("");
        tf_senha.setText("");
        cb_nivel.setSelectedItem("NÍVEL DE ACESSO");
        tf_id.setText("");
    }

    public void editarUsuarios() {
        String sql = "Update login set Usuario = ?,Senha = ?,Nivel = ? where id = ? ";

        try {
            pst = conecta.prepareStatement(sql);
            pst.setString(1, tf_usuario.getText());
            pst.setString(2, tf_senha.getText());
            pst.setString(3, cb_nivel.getSelectedItem().toString());
            pst.setInt(4, Integer.parseInt(tf_id.getText()));
            pst.executeUpdate();
            JOptionPane.showMessageDialog(null, "Usuário atualizado com sucesso");
            listarUsuarios();

        } catch (SQLException error) {
            JOptionPane.showMessageDialog(null, error);
        }
    }

    public void deletarUsuarios() {
        String sql = "Delete from login where id = ?";

        try {
            pst = conecta.prepareStatement(sql);
            pst.setInt(1, Integer.parseInt(tf_id.getText()));
            pst.execute();
            JOptionPane.showMessageDialog(null, "Usuário deletado com sucesso");
            listarUsuarios();
        } catch (SQLException error) {

            JOptionPane.showMessageDialog(null, error);
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tf_usuario = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        cb_nivel = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        tf_senha = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        tf_id = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jt_usuarios = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("E-KEY - Cadastrar Usuário");
        setResizable(false);
        getContentPane().setLayout(null);

        tf_usuario.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        getContentPane().add(tf_usuario);
        tf_usuario.setBounds(10, 30, 180, 30);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("USUÁRIO");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(10, 10, 56, 15);

        cb_nivel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cb_nivel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NÍVEL DE ACESSO", "OPERADOR", "ENCARREGADO", "ADMINISTRADOR" }));
        cb_nivel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        getContentPane().add(cb_nivel);
        cb_nivel.setBounds(10, 90, 180, 30);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("NÍVEL");
        getContentPane().add(jLabel3);
        jLabel3.setBounds(10, 70, 35, 15);

        tf_senha.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        getContentPane().add(tf_senha);
        tf_senha.setBounds(230, 30, 180, 30);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("SENHA");
        getContentPane().add(jLabel2);
        jLabel2.setBounds(230, 10, 41, 15);

        tf_id.setEditable(false);
        tf_id.setBackground(new java.awt.Color(255, 255, 255));
        tf_id.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        tf_id.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tf_idActionPerformed(evt);
            }
        });
        getContentPane().add(tf_id);
        tf_id.setBounds(610, 30, 40, 30);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setText("ID");
        getContentPane().add(jLabel4);
        jLabel4.setBounds(610, 10, 14, 15);

        jt_usuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jt_usuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jt_usuariosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jt_usuarios);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(0, 130, 660, 200);

        jButton4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Finish  (1).png"))); // NOI18N
        jButton4.setText("SALVAR");
        jButton4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4);
        jButton4.setBounds(10, 340, 120, 50);

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Information (1).png"))); // NOI18N
        jButton1.setText("EDITAR");
        jButton1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1);
        jButton1.setBounds(140, 340, 120, 50);

        jButton5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Eraser (1).png"))); // NOI18N
        jButton5.setText("EXCLUIR");
        jButton5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton5);
        jButton5.setBounds(270, 340, 120, 50);

        jButton3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Working (1).png"))); // NOI18N
        jButton3.setText("LIMPAR");
        jButton3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3);
        jButton3.setBounds(400, 340, 120, 50);

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Cancel (1).png"))); // NOI18N
        jButton2.setText("FECHAR");
        jButton2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2);
        jButton2.setBounds(530, 340, 120, 50);

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/Fundo E-Key.png"))); // NOI18N
        getContentPane().add(jLabel5);
        jLabel5.setBounds(0, 0, 670, 400);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void tf_idActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_idActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tf_idActionPerformed

    private void jt_usuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jt_usuariosMouseClicked
        mostraUsuarios();
    }//GEN-LAST:event_jt_usuariosMouseClicked

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        cadastrarUsuario();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        editarUsuarios();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        deletarUsuarios();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        Limpar();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Tela_CadastrarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Tela_CadastrarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Tela_CadastrarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Tela_CadastrarUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Tela_CadastrarUsuario().setVisible(true);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Tela_CadastrarUsuario.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cb_nivel;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jt_usuarios;
    private javax.swing.JTextField tf_id;
    private javax.swing.JTextField tf_senha;
    private javax.swing.JTextField tf_usuario;
    // End of variables declaration//GEN-END:variables
}
